/**
 * Created by hama on 2016/6/12.
 */

var express = require('express');
var fs = require('fs');
var router = express.Router();
var multer = require('multer');

var storage = multer.diskStorage({
    destination:'www/uploads',
    filename:function(req,file,callback){
        var petname = req.cookies.petname;
        callback(null,`${petname}.jpg`);
    }
})
var uploads = multer({storage});
//中间件来判断用户是否登录
function sign(req, res, next){
    if(req.cookies.petname){
        next()
    }
    else{
        if(req.xhr){
            function send(code,message){
                res.status(200).json({code,message});
            }
            // req.xhr通过请求头中的X-Requested-With判断是
            // 否是Ajax请求，Ajax请求默认都带有这个请求头
            send(res, 'signin error', '请重新登录...')
        }
        else{
            res.redirect('/signin')
        }
    }
}
router.get('/user',sign,function(req,res){
    res.render('user',{
        user: req.cookies.petname
    });
})

//头像，以用户名命名
router.post('/user', uploads.single('photo'), (req, res) => {
    res.status(200).json({ code: 'success', message: '上传成功' })
})
module.exports = router